package com.cccccc.filter;

import com.cccccc.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * --- 代码敲对！ ---
 *
 * @author CCCccc
 * @create 2025/8/22
 * 备注：
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private JwtUtils jwtUtils; // 注入JwtUtils工具类

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = jwtUtils.getToken(request); // 从请求中获取token
        if (!ObjectUtils.isEmpty(token) && SecurityContextHolder.getContext().getAuthentication() == null){
            // 如果token不为空且SecurityContextHolder中没有认证信息，则进行认证
            Claims claims = jwtUtils.parseToken(token); // 解析token
            List<String> authorities = claims.get("perms",List.class); // 获取权限信息
            String authoritiesString = String.join(",", authorities); // 将权限信息拼接成字符串
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(claims.get("username"),// 创建认证信息
                    null, AuthorityUtils.commaSeparatedStringToAuthorityList(authoritiesString));// 创建认证信息
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));// 设置认证信息
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);// 将认证信息放入SecurityContextHolder中
        }
        filterChain.doFilter(request, response); // 继续过滤器链
    }
}
